"""
AI历史消息记忆管理数据模型
"""

from datetime import datetime
from enum import Enum
from typing import List, Optional, Dict, Any

from pydantic import BaseModel, Field, field_validator, ConfigDict, model_serializer


class MemoryStatus(int, Enum):
    """记忆状态枚举"""
    TEMPORARY = 1  # 临时
    DAILY = 2  # 当天
    PERMANENT = 3  # 永久

    @classmethod
    def validate_status(cls, value):
        """验证并转换status值"""
        if isinstance(value, int):
            if value in [1, 2, 3]:
                return value
            else:
                raise ValueError(f"无效的状态值: {value}，必须是 1, 2, 3 中的一个")
        elif isinstance(value, str):
            try:
                int_value = int(value)
                if int_value in [1, 2, 3]:
                    return int_value
                else:
                    raise ValueError(f"无效的状态值: {value}，必须是 1, 2, 3 中的一个")
            except ValueError:
                raise ValueError(f"无效的状态值: {value}，必须是 1, 2, 3 中的一个")
        else:
            raise ValueError(f"状态值必须是整数，当前类型: {type(value)}")


class ImportanceLevel(int, Enum):
    """重要程度枚举"""
    VERY_LOW = 1  # 很低
    LOW = 2  # 低
    MEDIUM = 3  # 中等
    HIGH = 4  # 高
    VERY_HIGH = 5  # 很高

    @classmethod
    def validate_importance(cls, value):
        """验证并转换importance_level值"""
        if isinstance(value, int):
            if 1 <= value <= 5:
                return value
            else:
                raise ValueError(f"无效的重要程度: {value}，必须是 1-5 之间的数字")
        elif isinstance(value, str):
            try:
                int_value = int(value)
                if 1 <= int_value <= 5:
                    return int_value
                else:
                    raise ValueError(f"无效的重要程度: {value}，必须是 1-5 之间的数字")
            except ValueError:
                raise ValueError(f"无效的重要程度: {value}，必须是 1-5 之间的数字")
        else:
            raise ValueError(f"重要程度必须是整数，当前类型: {type(value)}")


class AIWebMemoryHis(BaseModel):
    """AI历史消息记忆管理实体类"""
    id: Optional[int] = Field(None, description="自增主键，唯一标识每条历史消息")
    scene_id: str = Field(..., max_length=64, description="场景 ID，用于区分不同应用场景")
    agent_id: str = Field(..., max_length=64, description="智能体 ID，标识处理消息的 AI 主体")
    session_id: str = Field(..., max_length=64, description="对话 ID，关联同一次对话的所有消息")
    user_id: str = Field(..., max_length=64, description="用户 ID，标识消息所属用户")
    his_text: str = Field(..., description="历史消息内容，支持长文本存储")
    create_time: datetime = Field(..., description="消息创建时间，自动记录消息生成时间")
    update_time: Optional[datetime] = Field(None, description="最后更新时间，标注或状态变更时更新")
    status: int = Field(default=1, description="状态标识：1 = 临时 / 2 = 当天 / 3 = 永久，默认 1")
    importance_level: int = Field(default=3, description="重要程度：1-5 级，默认 3")
    tags: Optional[str] = Field(None, max_length=255, description="自定义标签，多个标签用逗号分隔")
    annotation: Optional[str] = Field(None, description="标注内容，用户对消息的备注或说明")
    extra_info: Optional[Dict[str, Any]] = Field(None, description="扩展信息，存储 JSON 格式的附加数据")

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'created_at' in data and data['created_at']:
            data['created_at'] = data['created_at'].isoformat()
        if 'updated_at' in data and data['updated_at']:
            data['updated_at'] = data['updated_at'].isoformat()
        return data

    model_config = ConfigDict(from_attributes=True)

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        return MemoryStatus.validate_status(v)

    @field_validator('importance_level', mode='before')
    @classmethod
    def validate_importance_level_field(cls, v):
        """验证importance_level字段"""
        return ImportanceLevel.validate_importance(v)

    @field_validator('tags')
    @classmethod
    def validate_tags(cls, v):
        """验证标签格式"""
        if v is not None and v.strip():
            # 检查标签是否包含非法字符
            if '，' in v:  # 中文逗号
                raise ValueError('标签分隔符请使用英文逗号')
            # 验证标签长度
            tags_list = [tag.strip() for tag in v.split(',') if tag.strip()]
            if len(tags_list) > 10:
                raise ValueError('标签数量不能超过10个')
            for tag in tags_list:
                if len(tag) > 20:
                    raise ValueError('单个标签长度不能超过20个字符')
        return v


class AIWebMemoryHisCreate(BaseModel):
    """创建历史消息记忆请求模型"""
    scene_id: str = Field(..., max_length=64, description="场景 ID，用于区分不同应用场景")
    agent_id: str = Field(..., max_length=64, description="智能体 ID，标识处理消息的 AI 主体")
    session_id: str = Field(..., max_length=64, description="对话 ID，关联同一次对话的所有消息")
    user_id: str = Field(..., max_length=64, description="用户 ID，标识消息所属用户")
    his_text: str = Field(..., description="历史消息内容，支持长文本存储")
    status: int = Field(default=1, description="状态标识：1 = 临时 / 2 = 当天 / 3 = 永久，默认 1")
    importance_level: int = Field(default=3, description="重要程度：1-5 级，默认 3")
    tags: Optional[str] = Field(None, max_length=255, description="自定义标签，多个标签用逗号分隔")
    annotation: Optional[str] = Field(None, description="标注内容，用户对消息的备注或说明")
    extra_info: Optional[Dict[str, Any]] = Field(None, description="扩展信息，存储 JSON 格式的附加数据")

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        return MemoryStatus.validate_status(v)

    @field_validator('importance_level', mode='before')
    @classmethod
    def validate_importance_level_field(cls, v):
        """验证importance_level字段"""
        return ImportanceLevel.validate_importance(v)

    @field_validator('tags')
    @classmethod
    def validate_tags(cls, v):
        """验证标签格式"""
        if v is not None and v.strip():
            if '，' in v:  # 中文逗号
                raise ValueError('标签分隔符请使用英文逗号')
            tags_list = [tag.strip() for tag in v.split(',') if tag.strip()]
            if len(tags_list) > 10:
                raise ValueError('标签数量不能超过10个')
            for tag in tags_list:
                if len(tag) > 20:
                    raise ValueError('单个标签长度不能超过20个字符')
        return v


class AIWebMemoryHisUpdate(BaseModel):
    """更新历史消息记忆请求模型"""
    his_text: Optional[str] = Field(None, description="历史消息内容，支持长文本存储")
    status: Optional[int] = Field(None, description="状态标识：1 = 临时 / 2 = 当天 / 3 = 永久")
    importance_level: Optional[int] = Field(None, description="重要程度：1-5 级")
    tags: Optional[str] = Field(None, max_length=255, description="自定义标签，多个标签用逗号分隔")
    annotation: Optional[str] = Field(None, description="标注内容，用户对消息的备注或说明")
    extra_info: Optional[Dict[str, Any]] = Field(None, description="扩展信息，存储 JSON 格式的附加数据")

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        if v is not None:
            return MemoryStatus.validate_status(v)
        return v

    @field_validator('importance_level', mode='before')
    @classmethod
    def validate_importance_level_field(cls, v):
        """验证importance_level字段"""
        if v is not None:
            return ImportanceLevel.validate_importance(v)
        return v

    @field_validator('tags')
    @classmethod
    def validate_tags(cls, v):
        """验证标签格式"""
        if v is not None and v.strip():
            if '，' in v:  # 中文逗号
                raise ValueError('标签分隔符请使用英文逗号')
            tags_list = [tag.strip() for tag in v.split(',') if tag.strip()]
            if len(tags_list) > 10:
                raise ValueError('标签数量不能超过10个')
            for tag in tags_list:
                if len(tag) > 20:
                    raise ValueError('单个标签长度不能超过20个字符')
        return v


class AIWebMemoryHisResponse(BaseModel):
    """历史消息记忆响应模型"""
    id: int
    scene_id: str
    agent_id: str
    scene_name: Optional[str] = Field(None, description="场景名称")
    agent_name: Optional[str] = Field(None, description="智能体名称")
    session_id: str
    user_id: str
    his_text: str
    create_time: datetime
    update_time: Optional[datetime]
    status: int
    importance_level: int
    tags: Optional[str]
    annotation: Optional[str]
    extra_info: Optional[Dict[str, Any]]

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'created_at' in data and data['created_at']:
            data['created_at'] = data['created_at'].isoformat()
        if 'updated_at' in data and data['updated_at']:
            data['updated_at'] = data['updated_at'].isoformat()
        return data

    model_config = ConfigDict(from_attributes=True)


class AIWebMemoryHisQueryParams(BaseModel):
    """历史消息记忆查询参数"""
    scene_id: Optional[str] = Field(None, description="场景ID筛选")
    agent_id: Optional[str] = Field(None, description="智能体ID筛选")
    scene_name: Optional[str] = Field(None, description="场景名称筛选（模糊匹配）")
    agent_name: Optional[str] = Field(None, description="智能体名称筛选（模糊匹配）")
    session_id: Optional[str] = Field(None, description="对话ID筛选")
    user_id: Optional[str] = Field(None, description="用户ID筛选")
    status: Optional[int] = Field(None, description="状态筛选")
    importance_level: Optional[int] = Field(None, description="重要程度筛选")
    tags: Optional[str] = Field(None, description="标签筛选（包含匹配）")
    keyword: Optional[str] = Field(None, description="消息内容关键词搜索")
    start_time: Optional[datetime] = Field(None, description="开始时间筛选")
    end_time: Optional[datetime] = Field(None, description="结束时间筛选")


class AIWebMemoryHisListResponse(BaseModel):
    """历史消息记忆列表响应模型"""
    total: int = Field(..., description="总数量")
    items: List[AIWebMemoryHisResponse] = Field(..., description="历史消息记忆列表")


class AIWebMemoryHisStatusUpdate(BaseModel):
    """历史消息记忆状态更新模型"""
    status: int = Field(..., description="新状态")

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        return MemoryStatus.validate_status(v)


class AIWebMemoryHisImportanceUpdate(BaseModel):
    """历史消息记忆重要程度更新模型"""
    importance_level: int = Field(..., description="新重要程度")

    @field_validator('importance_level', mode='before')
    @classmethod
    def validate_importance_level_field(cls, v):
        """验证importance_level字段"""
        return ImportanceLevel.validate_importance(v)


class AIWebMemoryHisBatchUpdate(BaseModel):
    """批量更新历史消息记忆模型"""
    ids: List[int] = Field(..., description="要更新的记录ID列表")
    status: Optional[int] = Field(None, description="批量更新状态")
    importance_level: Optional[int] = Field(None, description="批量更新重要程度")
    tags: Optional[str] = Field(None, description="批量更新标签")

    @field_validator('ids')
    @classmethod
    def validate_ids_not_empty(cls, v):
        """验证ID列表不为空"""
        if not v or len(v) == 0:
            raise ValueError('ID列表不能为空')
        return v

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        if v is not None:
            return MemoryStatus.validate_status(v)
        return v

    @field_validator('importance_level', mode='before')
    @classmethod
    def validate_importance_level_field(cls, v):
        """验证importance_level字段"""
        if v is not None:
            return ImportanceLevel.validate_importance(v)
        return v


class AIWebMemoryHisBatchDelete(BaseModel):
    """批量删除历史消息记忆模型"""
    ids: List[int] = Field(..., description="要删除的记录ID列表")

    @field_validator('ids')
    @classmethod
    def validate_ids_not_empty(cls, v):
        """验证ID列表不为空"""
        if not v or len(v) == 0:
            raise ValueError('ID列表不能为空')
        return v


class AIWebMemoryHisBatchDeleteByDate(BaseModel):
    """按日期批量删除历史消息记忆模型"""
    start_date: str = Field(..., description="开始日期，格式：YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS")
    end_date: str = Field(..., description="结束日期，格式：YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS")
    status: Optional[int] = Field(None, description="状态筛选")
    scene_id: Optional[str] = Field(None, description="场景ID筛选")
    scene_name: Optional[str] = Field(None, description="场景名称筛选")
    agent_id: Optional[str] = Field(None, description="智能体ID筛选")
    agent_name: Optional[str] = Field(None, description="智能体名称筛选")

    @field_validator('start_date', 'end_date')
    @classmethod
    def validate_date_format(cls, v):
        """验证日期格式"""
        import re
        from datetime import datetime

        # 支持的日期格式
        date_patterns = [
            r'^\d{4}-\d{2}-\d{2}$',  # YYYY-MM-DD
            r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$'  # YYYY-MM-DD HH:MM:SS
        ]

        if not any(re.match(pattern, v) for pattern in date_patterns):
            raise ValueError('日期格式错误，支持格式：YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS')

        # 尝试解析日期
        try:
            if len(v) == 10:  # YYYY-MM-DD
                datetime.strptime(v, '%Y-%m-%d')
            else:  # YYYY-MM-DD HH:MM:SS
                datetime.strptime(v, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            raise ValueError('无效的日期值')

        return v

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        if v is not None:
            return MemoryStatus.validate_status(v)
        return v


class AIWebMemoryHisStatistics(BaseModel):
    """历史消息记忆统计模型"""
    total_count: int = Field(..., description="总消息数量")
    temporary_count: int = Field(..., description="临时消息数量")
    daily_count: int = Field(..., description="当天消息数量")
    permanent_count: int = Field(..., description="永久消息数量")
    importance_distribution: Dict[int, int] = Field(..., description="重要程度分布")
    recent_activity: List[Dict[str, Any]] = Field(..., description="最近活动统计")
